﻿using CrawlerCore.Helper;
using CrawlerCore.XmlData;
using CrawlerCore.XmlDataTemp;
using HtmlAgilityPack;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace CrawlerCore
{
    public class Tigerair
    {
        private CrawlerHelper crawlerHelper { get; set; }
        private string address = "http://booking.tigerair.com/Search.aspx";
        public Tigerair()
        {
            crawlerHelper = new CrawlerHelper();
        }
        public string getPostData(SearchInputService myInput)
        {
            StringBuilder postData = new StringBuilder("");
            string waytype = "RoundTrip";
            if (!myInput.IsRoundTrip)
                waytype = "OneWay";
            postData.Append("__EVENTTARGET=");
            postData.Append("&__EVENTARGUMENT=");
            postData.Append("&__VIEWSTATE=%2FwEPDwUBMGRk7p3dDtvn3PMYYJ9u4RznKUiVx98%3D");
            postData.Append("&ControlGroupSearchView%24AvailabilitySearchInputSearchView%24RadioButtonMarketStructure=" + waytype);
            postData.Append("&ControlGroupSearchView%24AvailabilitySearchInputSearchView%24HiddenFieldExternalRateId=");
            postData.Append("&ControlGroupSearchView_AvailabilitySearchInputSearchVieworiginStation1=" + myInput.DepartureCode);
            postData.Append("&ControlGroupSearchView%24AvailabilitySearchInputSearchView%24TextBoxMarketOrigin1=" + myInput.DepartureCode);
            postData.Append("&ControlGroupSearchView_AvailabilitySearchInputSearchViewdestinationStation1=" + myInput.ArrivalCode);
            postData.Append("&ControlGroupSearchView%24AvailabilitySearchInputSearchView%24TextBoxMarketDestination1=" + myInput.ArrivalCode);
            postData.Append("&ControlGroupSearchView%24AvailabilitySearchInputSearchView%24DropDownListMarketDay1=" + myInput.DepartTime.ToString("dd"));
            postData.Append("&ControlGroupSearchView%24AvailabilitySearchInputSearchView%24DropDownListMarketMonth1=" + myInput.DepartTime.ToString("yyyy-MM"));
            postData.Append("&ControlGroupSearchView%24AvailabilitySearchInputSearchView%24DropDownListMarketDateRange1=1%7C1");
            postData.Append("&date_picker=" + myInput.DepartTime.ToString("yyyy-MM-dd"));
            postData.Append("&pageToken=");


            if (myInput.IsRoundTrip)
            {
                postData.Append("&ControlGroupSearchView_AvailabilitySearchInputSearchVieworiginStation2=");
                postData.Append("&ControlGroupSearchView%24AvailabilitySearchInputSearchView%24TextBoxMarketOrigin2=");
                postData.Append("&ControlGroupSearchView_AvailabilitySearchInputSearchViewdestinationStation2=");
                postData.Append("&ControlGroupSearchView%24AvailabilitySearchInputSearchView%24TextBoxMarketDestination2=");
                postData.Append("&ControlGroupSearchView%24AvailabilitySearchInputSearchView%24DropDownListMarketDay2=" + myInput.ReturnTime.ToString("dd"));
                postData.Append("&ControlGroupSearchView%24AvailabilitySearchInputSearchView%24DropDownListMarketMonth2=" + myInput.ReturnTime.ToString("yyyy-MM"));
                postData.Append("&ControlGroupSearchView%24AvailabilitySearchInputSearchView%24DropDownListMarketDateRange2=1%7C1");
                postData.Append("&date_picker=" + myInput.ReturnTime.ToString("yyyy-MM-dd"));
            }
            postData.Append("&ControlGroupSearchView%24AvailabilitySearchInputSearchView%24DropDownListPassengerType_ADT=" + myInput.Adults);
            postData.Append("&ControlGroupSearchView%24AvailabilitySearchInputSearchView%24DropDownListPassengerType_CHD=" + myInput.Children);
            postData.Append("&ControlGroupSearchView%24AvailabilitySearchInputSearchView%24DropDownListPassengerType_INFANT=" + myInput.Inf);
            postData.Append("&ControlGroupSearchView%24AvailabilitySearchInputSearchView%24HIDDENPROMOCODE=");
            postData.Append("&ControlGroupSearchView%24AvailabilitySearchInputSearchView%24DropDownListMCCCurrency=default");
            postData.Append("&hiddendAdultSelection=" + myInput.Adults);
            postData.Append("&hiddendChildSelection=" + myInput.Children);
            postData.Append("&ControlGroupSearchView%24ButtonSubmit=get+flights");
            return postData.ToString();
        }
        public RootTemp CreateXmlDocument(SearchInputService input)
        {
            //CookieCollection c= crawlerHelper.getCookieCollection(adress, "POST", getPostData(input));
            HtmlDocument d = crawlerHelper.getDocument(address, "POST", getPostData(input), null);
            RootTemp rootxml = new RootTemp();
            rootxml.Departure = input.DepartureCode;
            rootxml.Arrival = input.ArrivalCode;
            rootxml.AirLine = AirLineName.tiger;
            rootxml.blocks = new List<Block>();
            rootxml.AirLine = AirLineName.tiger;
            Block b = new Block();
            HtmlNode node = d.DocumentNode.SelectSingleNode("//div[contains(@class,'depart-flight')]");
            b.outBound = getOutInBound(node);
            node = d.DocumentNode.SelectSingleNode("//div[contains(@class,'return-flight')]");
            b.inBound = getOutInBound(node);
            rootxml.blocks.Add(b);
            return rootxml;
            
        }

        private OutInBoundTemp getOutInBound(HtmlNode htmlNode)
        {
            OutInBoundTemp result = null;
            try
            {
                result = new OutInBoundTemp();
                HtmlNodeCollection nodebody = htmlNode.SelectNodes("table[@class='select-flight']/tbody/tr");
                result.Items = getListItems(nodebody);
            }
            catch
            {

            }
            return result;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="htmlNodeCollection">moi the tr chua mot item</param>
        /// <returns></returns>
        private List<ItemTemp> getListItems(HtmlNodeCollection htmlNodeCollection)
        {
            List<ItemTemp> liItems = null;
            try
            {
                liItems = new List<ItemTemp>();
                int id = 0;
                foreach(HtmlNode node in htmlNodeCollection)
                {
                    try
                    {
                        ItemTemp item = new ItemTemp();
                        HtmlNode nodeTemp = node.SelectSingleNode("td[2]");
                        item.prices = getListprices(nodeTemp);
                        nodeTemp = node.SelectSingleNode("td[1]");
                        item.Segments = getListSegments(nodeTemp);
                        item.Id = id;
                        item.TotalTime = node.SelectSingleNode("td[1]//ul/li[3]/strong").InnerText.Replace("Total Duration: ","");
                        item.TotalTime = item.TotalTime.Substring(0, item.TotalTime.IndexOf('m') + 1);
                        liItems.Add(item);
                        //chi lay 4 item
                        if (liItems.Count > 3)
                            break;
                        id++;
                    }
                    catch { }
                }
            }
            catch
            { }
            return liItems;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="htmlNode"></param>
        /// <returns></returns>
        private List<SegmentTemp> getListSegments(HtmlNode htmlNode)
        {
            List<SegmentTemp> liS = null;
            try
            {
                liS = new List<SegmentTemp>();
                int id = 1;
                try
                {
                    SegmentTemp prevS = null;
                    HtmlNodeCollection ncTable=htmlNode.SelectNodes(".//div[@class='stops-overlay']/table");
                    foreach (HtmlNode nodeS in ncTable)
                    {
                        HtmlNode nodeSTemp = nodeS.SelectSingleNode("tbody");
                        SegmentTemp s = new SegmentTemp();
                        s.flightNo = nodeSTemp.SelectSingleNode("tr[1]/td[2]").InnerText;
                        s.AirLine = s.flightNo.Substring(0, 2);
                        string departDate = nodeSTemp.SelectSingleNode("tr[2]/td[2]").InnerText;
                        string departTime=nodeSTemp.SelectSingleNode("tr[3]/td[2]").InnerText.Split('-')[1];
                        s.departureTime =DateTime.Parse(departDate+" "+departTime, CultureInfo.GetCultureInfo("en-gb"));
                        s.arriveTime = DateTime.Parse(departDate + nodeSTemp.SelectSingleNode("tr[4]/td[2]").InnerText.Split('-')[1], CultureInfo.GetCultureInfo("en-gb"));

                        s.Departure = nodeSTemp.SelectSingleNode("tr[3]/td[2]").InnerText.Split('-')[0];
                        s.Arrive = nodeSTemp.SelectSingleNode("tr[4]/td[2]").InnerText.Split('-')[0];
                        s.duration = nodeSTemp.SelectSingleNode("tr[5]/td[2]").InnerText;
                        if(prevS!=null)
                        {
                            prevS.layOver = nodeSTemp.SelectSingleNode("tr[6]/td[2]").InnerText; ;
                        }
                        //check lai ngay den
                        s.arriveTime =DateTimeHelper.getDateAbacusArriveTime(s.departureTime, s.arriveTime.ToString());
                        prevS = s;
                        s.Id = id;
                        liS.Add(s);
                        id++;
                    }
                }
                catch { }
            }
            catch { }
            return liS;
        }

        private List<PriceTemp> getListprices(HtmlNode htmlNode)
        {
            List<PriceTemp> liP = null;
            try
            {
                liP = new List<PriceTemp>();
                PriceTemp p = new PriceTemp();
                p.name = "";
                p.price = decimal.Parse(htmlNode.SelectSingleNode(".//span[@class='price']").InnerText.Replace("USD ", "")) * MoneyRate.MONEY_RATE;
                liP.Add(p);
            }
            catch { }
            return liP;
        }

    }
}
